#include "attributemodel.h"

AttributeModel::AttributeModel(AED_Archtype *arch,QObject *parent) :
    QAbstractTableModel(parent)
{
    m_attributes = arch->GetAttributes();
}

int AttributeModel::rowCount(const QModelIndex & parent) const{
    return m_attributes->size();
}

int AttributeModel::columnCount(const QModelIndex & parent) const{
    return 2;
}

QVariant AttributeModel::data ( const QModelIndex & index, int role) const{
    if(role==Qt::DisplayRole||role==Qt::EditRole){
        int row = index.row();


        AED_Attribute attr = (*m_attributes)[row];

        QVariant var;

        if(index.column()==0)
            var = attr.GetType();
        else if(index.column()==1)
            var = attr.GetName();
        else
            return QVariant(QVariant::Invalid);
        return var;
    }
    return QVariant(QVariant::Invalid);
}

QVariant AttributeModel::headerData ( int section, Qt::Orientation orientation, int role) const{
    if(orientation==Qt::Horizontal){
        if (role==Qt::DisplayRole||role==Qt::EditRole){
            if(section==0)
                return "Type";
            if(section==1)
                return "Name";
            else
                return QVariant(QVariant::Invalid);
        }else{
            return QVariant(QVariant::Invalid);
        }
    }else{
        if (role==Qt::DisplayRole||role==Qt::EditRole){
            QVariant h(QVariant::Int);
            h=section+1;
            return h;
        }else{
            return QVariant(QVariant::Invalid);
        }
    }
    return QVariant(QVariant::Invalid);
}

bool AttributeModel::setData(const QModelIndex &index, const QVariant &value, int role){
    int row = index.row();
    int column = index.column();

    if(index.isValid() && role==Qt::EditRole){
        if(column==0){
            (*m_attributes)[row].SetType(value.toString());
        }else if(column==1){
            (*m_attributes)[row].SetName(value.toString());
        }else{
            return false;
        }
        emit dataChanged(index,index);
        return true;
    }

    return false;
}

Qt::ItemFlags AttributeModel::flags(const QModelIndex &index) const{
    Qt::ItemFlags flags;

    flags = Qt::ItemIsEnabled|Qt::ItemIsSelectable|Qt::ItemIsEditable;

    return flags;
}

void AttributeModel::AddAttribute(const QString &type, const QString &name){
    m_attributes->append(AED_Attribute(type,name));

    emit layoutChanged();
}

void AttributeModel::RemoveAttribute(int index){
    m_attributes->removeOne((*m_attributes)[index]);
    emit layoutChanged();
}
